package com.sk.rpcAssist.io.protocol;

import java.io.*;

/*
 * description：java自带的序列化工具
 *
 * @param
 * @return
 * @throws (方法有异常)
 * @see 引用类名
 * @author 孙文斌
 * @date: 2021/3/4
 **/
public class DefaultMessageProtocol implements MessageProtocolInter {

    public static final String PROTOCOLCODE = "p1";

    public static DefaultMessageProtocol getInstance() {
        return new DefaultMessageProtocol();
    }

    @Override
    public RpcRequest serviceToRequest(InputStream inputStream) {
        RpcRequest request = new RpcRequest();
        try {
            ObjectInputStream input = new ObjectInputStream(inputStream);
            request.setClassName(input.readUTF());
            request.setMethodName(input.readUTF());
            request.setParameterTypes((Class<?>[]) input.readObject());
            request.setArguments((Object[]) input.readObject());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return request;
    }

    @Override
    public void serviceGetResponse(RpcResponse response, OutputStream outputStream) {
        try {
            ObjectOutputStream output = new ObjectOutputStream(outputStream);
            output.writeBoolean(response.getError());
            output.writeObject(response.getResult());
            output.writeObject(response.getErrorMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void clientToRequest(RpcRequest request, OutputStream outputStream) {
        try {
            ObjectOutputStream ouput = new ObjectOutputStream(outputStream);
            ouput.writeUTF(request.getClassName());
            ouput.writeUTF(request.getMethodName());
            ouput.writeObject(request.getParameterTypes());
            ouput.writeObject(request.getArguments());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public RpcResponse clientGetResponse(InputStream inputStream) {
        RpcResponse response = new RpcResponse();
        try {
            ObjectInputStream input = new ObjectInputStream(inputStream);
            response.setError(input.readBoolean());
            response.setResult(input.readObject());
            response.setErrorMessage((String) input.readObject());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }
}